package com.zoweunion.mechanic.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

public class DateUtil {

    public static Object weekObject(int week){
        String str="";
        switch(week){
            case 1:
                str="星期一";
                break;
            case 2:
                str="星期二";
                break;
            case 3:
                str="星期三";
                break;
            case 4:
                str="星期四";
                break;
            case 5:
                str="星期五";
                break;
            case 6:
                str="星期六";
                break;
            case 7:
                str="星期日";
                break;
            default:

        }
        return str;
    }


	/**
     * 日期格式字符串转换成时间戳 
     * @param date_str 字符串日期
     * @param format 如：yyyy-MM-dd HH:mm:ss 
     * @return 
     */  
    public static long date2TimeStamp(String date_str,String format){
        try {  
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.parse(date_str).getTime()/1000;
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return 0;
    }

    /**
     * UTC格式的时间字符串转换成本地时间易读的时间字符串
     * @param
     * @return
     */
    public static String utcToLocalAddOne(String utcTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date utcDate = null;
        try {
            utcDate = sdf.parse(utcTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd ");
        localFormater.setTimeZone(TimeZone.getDefault());
        Calendar c = Calendar.getInstance();
        c.setTime(utcDate);
        c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
        Date tomorrow = c.getTime();
        String localTime = localFormater.format(tomorrow.getTime());
        return localTime;
    }


    /**
     * utc时间转成local时间
     * @param utcTime
     * @return
     */
    public static String utcToLocal(String utcTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date utcDate = null;
        try {
            utcDate = sdf.parse(utcTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd ");
        localFormater.setTimeZone(TimeZone.getDefault());
        String localTime = localFormater.format(utcDate.getTime());
//        try {
//            locatlDate = sdf.parse(localTime);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        return localTime;
    }


    /**
     * 获取当前一周的所有日期
     * @return
     */
    public static List<Date> DateList() throws Exception {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate inputDate = LocalDate.now();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        TemporalAdjuster FIRST_OF_WEEK =
                TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate.getDayOfWeek().getValue()- DayOfWeek.MONDAY.getValue()));

        //TODO 本周结束时间
        TemporalAdjuster LAST_OF_WEEK =
                TemporalAdjusters.ofDateAdjuster(localDate -> localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue()));
        String weekStart = df.format(inputDate.with(FIRST_OF_WEEK));
        String weekEnd = df.format(inputDate.with(LAST_OF_WEEK));

        String start_time=weekStart;//本周第一天
        String end_time=weekEnd;  //本周最后一天
        //格式化日期
        Date dBegin = sdf.parse(start_time);
        Date dEnd = sdf.parse(end_time);
        return findDates(dBegin, dEnd);
    }

    /**
     * 计算一周的所有日期
     * @param dBegin
     * @param dEnd
     * @return
     */
    public static List<Date> findDates(Date dBegin, Date dEnd) {
        List<Date> lDate = new ArrayList<Date>();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime()))
        {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }

    public static String formatTime(LocalDateTime localDateTime){
        return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    public static LocalDateTime parseTime(String dateTime) {
        return LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    public static String formatDate(LocalDate localDate){
        return localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String formatDate(Date localDate){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(localDate);
    }

    public static LocalDate parseDate(String date) {
        return LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static int getDays(LocalDate startDate, LocalDate endDate) {
        return Period.between(startDate, endDate).getDays();
    }

    public static int getMonths(LocalDate startDate, LocalDate endDate) {
        return Period.between(startDate, endDate).getMonths();
    }

    public static long dateDiff(String startTime, String endTime, String format) throws Exception {
        //按照传入的格式生成一个simpledateformate对象
        SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 1000*24*60*60;//一天的毫秒数
        long nh = 1000*60*60;//一小时的毫秒数
        long nm = 1000*60;//一分钟的毫秒数
        long ns = 1000;//一秒钟的毫秒数
        long diff;
        //获得两个时间的毫秒时间差异
        diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
        long day = diff/nd;//计算差多少天
        long hour = diff%nd/nh;//计算差多少小时
        long min = diff%nd%nh/nm;//计算差多少分钟
        long sec = diff%nd%nh%nm/ns;//计算差多少秒//输出结果
        System.out.println("时间相差："+day+"天"+hour+"小时"+min+"分钟"+sec+"秒。");
        return min ;
    }


    public static long getDistanceMinute(LocalDateTime startDate, LocalDateTime endDate) {
        return Duration.between(startDate, endDate).toMinutes();
    }

    public static LocalDateTime toLocalDateTime(LocalDate date, boolean isStart) {
        if (isStart) {
            return LocalDateTime.of(date.getYear(), date.getMonth(), date.getDayOfMonth(), 0, 0, 0);
        } else {
            return LocalDateTime.of(date.getYear(), date.getMonth(), date.getDayOfMonth(), 23, 59, 59);
        }
    }
    public static LocalDate toLocalDate(LocalDateTime time) {
        return LocalDate.of(time.getYear(), time.getMonth(), time.getDayOfMonth());
    }

    public static String getHHmm(String dateTime){
        return dateTime.substring(11, 16);
    }
    public static String getMMddHHmm(String dateTime){
        return dateTime.substring(5, 16);
    }

    /**
     * 格式化时间戳
     *
     * @param timestamp
     * @return
     */
    public static String formatTimestamp(Timestamp timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp.getTime());
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 格式化时间戳
     *
     * @param timestamp
     * @return
     */
    public static LocalDateTime formatTimestampToTime(Timestamp timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp.getTime());
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }


    public static void main(String[] args) throws Exception {


        long min = DateUtil.dateDiff("2014-05-27 13:00:00","2014-05-27 13:30:00","yyyy-MM-dd HH:mm:ss");
        System.out.println(min);
	}
}
